package com.jack.hhitseat.task;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.fastjson.JSON;
import com.jack.hhitseat.bean.Hhit;
import com.jack.hhitseat.bean.Login;
import com.jack.hhitseat.bean.User;
import com.jack.hhitseat.service.HttpClient;
import com.jack.hhitseat.service.impl.GinfoLogService;
import com.jack.hhitseat.service.impl.HhitService;
import com.jack.hhitseat.service.impl.LogServiceImpl;
import com.jack.hhitseat.service.impl.LoginServiceImpl;
import com.jack.hhitseat.service.impl.UserServiceImpl;
import com.jack.hhitseat.utils.MyUtils;

@Component
@Controller
@EnableScheduling   // 开启定时任务
@EnableAsync        // 开启多线程
public class BookTask {
	@Autowired
	HttpClient httpClient;
	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private LoginServiceImpl loginServiceImpl;
	@Autowired
	private HhitService hhitService;
	@Autowired
	private GinfoLogService ginfoLogService;
	@Autowired
	private LogServiceImpl logService;
	
	private final Logger logger = LoggerFactory.getLogger(MyTask.class);
	private final static String KEY = "0";
	private static ConcurrentMap<String, String> sessionMap = new ConcurrentHashMap<>(64);
	//线程池--设置线程数
	private static ExecutorService executorService = Executors.newFixedThreadPool(16);
	private static ExecutorService executorService2 = Executors.newFixedThreadPool(16);
	private static List<User> users = new ArrayList<>();
	
	//定时登录
	@Scheduled(cron = "00 23 5 * * ?")
    public void getSession() {
		init();
    }
	
	//首先请求对的验证码
	@Scheduled(cron = "35 28 5 * * ?")
    public void qqyzm() {
		logger.warn("######请求验证码");
		for (User user : users) {
			executorService.execute(new YzmRunnable(user, sessionMap));
		}
    }
	
/***************************************************************************/
	@Scheduled(cron = "02 30 5 * * ? ")		//抢座时间。
	public void reBookSeat2() {
		logger.warn("******启动抢座");
		int userNum = users.size();
		for (int i = userNum-1; i>=0; i--) {
			executorService.execute(new MyRunnable(users.get(i), sessionMap));
		}
	}
    
    public void init() {
    	sessionMap.clear();
    	users.clear();

//    	users = userService.getAllUserByDo(0, 15);
    	users = userService.getAllUserByDo();
//    	users = userService.getAllUserByStuNums();
    	logger.warn("本次抢座人数==={}", users.size());
    	
    	Iterator<User> it = users.iterator();
    	while(it.hasNext()){
    		User user = it.next();
    		String sission = login2wx(user);
    		//登录正常
			if(!sission.equals("LOGIN_ERR")) {
				String stuNum = user.getStuNum();
				//获取放入学号和Session
				sessionMap.put(stuNum, sission);
			}else {
				it.remove();
				user.setIsdo(0);
				userService.updateUser(user);
				Login login = new Login();
				login.setUserId(Integer.parseInt(user.getStuNum()));
				login.setIp(user.getUserName()+"***密码错误！！");
				login.setLoginTime(MyUtils.getNowDateTime());
				loginServiceImpl.addLogin(login);
			}
    	}
    }
    
    public String login2wx(User user) {
    	final int COUNT = 600;
    	 String url = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/login.aspx"; 
		  MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
		  String sjc = (System.currentTimeMillis()+120000)+"";
		  
		  params.add("act","dlogin");
		  params.add("number", KEY);
		  params.add("id", user.getStuNum()); 
		  params.add("pwd", user.getPassword()); 
		  params.add("role", "512");
		  params.add("_nocache", sjc);
		  
		ResponseEntity<String> response =  HttpClient.login2wx(url, null, params);
		String session = response.getHeaders().toString().split("ASP.NET_SessionId=")[1].split("; path=/; ")[0];
		
		for (int i = 1; i <= COUNT; i++) {
			String body =  response.getBody();
			if(!body.contains("验证码")) {
				if(body.contains("密码")) {
					logger.warn("{}***密码错误！！", user.getStuNum());
					return "LOGIN_ERR";
				} 
				//logger.warn("{}==={}==={}", i, user.getUserName(),session);
				return session;
			} else {
				httpClient.yzm(session);
				response =  HttpClient.login2wx(url, session, params);
			}
		}
		return session;
    }
    
    public void login2wxInfo(int num) {
    	final int COUNT = 600;
    	 String url = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/login.aspx"; 
		  MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
		  String sjc = (System.currentTimeMillis()+120000)+"";
		  
		  params.add("act","dlogin");
		  params.add("number", KEY);
		  params.add("id", num+""); 
		  params.add("pwd", num+""); 
		  params.add("role", "512");
		  params.add("_nocache", sjc);
		  
		ResponseEntity<String> response =  HttpClient.login2wx(url, null, params);
		String session = response.getHeaders().toString().split("ASP.NET_SessionId=")[1].split("; path=/; ")[0];
		
		for (int i = 1; i <= COUNT; i++) {
			String body =  response.getBody();
			if(!body.contains("验证码")) {
				if(body.contains("密码")) {
					logger.warn("密码错误===={}", num);
					return;
				}else if(body.contains("未授权")){
					logger.error("未授权用户==={}", num);
					return;
				}
				try {
					if(hhitService.count(num) >=1) {
						return;
					}
					body = body.split("\"data\":")[1].split(",\"ext\":null}")[0];
					
					Hhit info = new Hhit();
					info = JSON.parseObject(body, Hhit.class);
					info.setSno(info.getId());
					info.setId(null);
					info.setPwd(num+"");
					info.setCreateTime(MyUtils.getNowDateTime());
					hhitService.save(info);
				}catch (Exception e) {
					logger.error("num===="+num+"===", e);
				}
				return;
			} else {
				httpClient.yzm(session);
				response =  HttpClient.login2wx(url, session, params);
			}
		}
    }
}
